package com.arvinclub.model.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 公共 工具类
 * Created by zxy on 18/11/15.
 */
public class ToolsUtil
{

    /**
     * 两种日期格式
     */
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");

    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("YYYY年MM月dd日 HH:mm");

    /**
     * 保存图片
     */
    public static String saveIMG(MultipartFile[] files, String root) throws Exception
    {
        /*用来存到数据库中的filenames*/
        StringBuilder result;
        if (files != null && files.length > 0)
        {
            result = new StringBuilder();
            ImageSizeUtil.byte2Base64StringFun(files);
            for (int i = 0; i < files.length; i++)
                if (files[i] != null && !files[i].isEmpty())
                {
                    /*随机产生一个文件名*/
                    String filename = new Random().nextInt(1000) + files[i].getOriginalFilename();
                    files[i].transferTo(new File(root + "/static/file/images/" + filename));
                    /*文件名之间用回车拼接*/
                    if (i != 0) result.append(" \n ");
                    result.append(filename);
                }
            return result.length() == 0 ? null : result.toString();
        }

        return null;
    }

    /**
     * 获得格式化的今天日期
     */
    public static String getNowTimeString()
    {
        return LocalDateTime.now().format(formatter);
    }


}
